package cn.edu.ctbu.datajpa01.webapi;

import cn.edu.ctbu.datajpa01.domain.Administrator;
import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.domain.Teacher;
import cn.edu.ctbu.datajpa01.service.AdministratorService;
import cn.edu.ctbu.datajpa01.service.StudentService;
import cn.edu.ctbu.datajpa01.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/webapi/login")
public class LoginRestController {

    @Autowired
    StudentService studentService;

    @Autowired
    TeacherService teacherService;

    @Autowired
    AdministratorService administratorService;

    @GetMapping("/user")
    public int user(HttpServletRequest httprequest, String username, String password) {

        //判断用户名和密码是否存在
        List<Student> students = studentService.findByNoAndPassword(username,password);  //学生

        List<Teacher> teachers = teacherService.findByTnoAndPassword(username,password);  //教师

        List<Administrator> administrators= administratorService.findByNoAndPassword(username,password);  //管理员

        if (students.size() > 0) {
            //若存在，写入session

            HttpSession session = httprequest.getSession();

            session.setAttribute("userid", students.get(0).getId());

            session.setAttribute("user", students.get(0));

            return 2;  //学生登录成功，向前端的rs返回2

        }

        else if(teachers.size() > 0){

            HttpSession session = httprequest.getSession();

            session.setAttribute("userid", teachers.get(0).getId());

            session.setAttribute("user", teachers.get(0));

            return 1;  //教师登录成功，向前端的rs返回1

        }

        else if(administrators.size() > 0){

            HttpSession session = httprequest.getSession();

            session.setAttribute("userid", administrators.get(0).getId());

            session.setAttribute("user", administrators.get(0));

            return 3;  //管理员登录成功，向前端的rs返回3

        }

        else{

            //如果账号或密码不错误，向前端的rs返回-1
            return -1;

        }
    }
}